package com.calefk.modules.files 
{
	
    import com.adobe.images.JPGEncoder;
    import com.calefk.util.Logger;
    import flash.display.BitmapData;
    import flash.display.MovieClip;
    import flash.events.Event;
    import flash.net.URLLoader;
    import flash.net.URLLoaderDataFormat;
    import flash.net.URLRequest;
    import flash.net.URLRequestHeader;
    import flash.net.URLRequestMethod;
    import flash.utils.ByteArray;
	
	public class JpgCreator
	{
		
		private var clipToTransform: MovieClip;
		private var bmapData: BitmapData;
		private var jpgEncoder:JPGEncoder;
		private var jpgStream: ByteArray;
		private var clipwidth:Number;
		private var clipheight:Number;
		private var filename:String;
		private var urlLoad:URLLoader;
		
		public var fileIsDone:Boolean = false;
		
		public function JpgCreator() {
		}
		
		public function makeJpgFile(clip:MovieClip,wid:Number,hei:Number,name:String):void {
			fileIsDone = false;
			if (!clip) { return; }
			clipToTransform = clip;
			clipwidth = wid;
			clipheight = hei;
			filename = name + '.jpg';
			//
			encodeBitmap();
			prepareEncoder();
			createFilePHP();
		}
		
		private function encodeBitmap(): void {
			bmapData = new BitmapData (clipwidth, clipheight);
			bmapData.draw(clipToTransform);
		}
		
		private function prepareEncoder():void {
			jpgEncoder = new JPGEncoder(85);
			jpgStream = jpgEncoder.encode(bmapData);
		}
		
		private function createFilePHP():void {
			var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream");	
			//
			var jpgURLRequest:URLRequest = new URLRequest("make_jpg.php?name="+this.filename);
			jpgURLRequest.requestHeaders.push(header);
			jpgURLRequest.method = URLRequestMethod.POST;
			jpgURLRequest.data = jpgStream;
			//
			urlLoad = new URLLoader();
			urlLoad.dataFormat = URLLoaderDataFormat.TEXT;
			urlLoad.addEventListener(Event.COMPLETE, handleComplete);
			urlLoad.load(jpgURLRequest);
			
			Logger.echo('php begin');
			//
			//navigateToURL(jpgURLRequest,'_blank');
			//
		}
		
		private function handleComplete(event:Event):void {
			Logger.echo('php complete');
			fileIsDone = true;
		}
		
		public function clean():void {
			clipToTransform = null;
			bmapData = null;
			jpgEncoder = null;
			jpgStream = null;
		}
		
	}

}